<template>
  <div class="course-detail-container">
    <div class="course-detail-header">
      <h2>课程详情</h2>
    </div>

    <div class="course-detail-info">
      <div class="course-avatar">
        <img :src="course.avatar || defaultAvatar" class="course-avatar-large" alt="Course Image" />
      </div>
      <div class="course-basic-info">
        <el-descriptions :column="1">
          <el-descriptions-item label="课程ID">{{ course.id }}</el-descriptions-item>
          <el-descriptions-item label="课程名称">{{ course.name }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </div>

    <div class="course-classes-section">
      <div class="class-header" style="display: flex; justify-content: space-between; align-items: center;">
        <h3>关联班级</h3>
        <el-button type="primary" @click="openAddDialog">添加班级</el-button>
      </div>

      <el-table :data="classList" style="width: 100%">
        <el-table-column prop="name" label="班级名称"></el-table-column>
        <el-table-column prop="totals" label="学生数量"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="openEditDialog(scope.row)">修改</el-button>
            <el-button type="danger" @click="deleteClass(scope.row.id)">删除</el-button>
            <el-button type="success" @click="openImportDialog(scope.row)">导入学生</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加班级对话框 -->
      <el-dialog v-model="addDialogVisible" title="添加班级" width="30%">
        <el-form ref="addForm" :model="addClassForm" label-width="120px">
          <el-form-item label="班级名称">
            <el-input v-model="addClassForm.name" placeholder="请输入班级名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addClass">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 修改班级对话框 -->
      <el-dialog v-model="editDialogVisible" title="修改班级" width="30%">
        <el-form ref="editForm" :model="editClassForm" label-width="120px">
          <el-form-item label="班级名称">
            <el-input v-model="editClassForm.name" placeholder="请输入班级名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="updateClass">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 导入学生名单对话框 -->
      <el-dialog v-model="importDialogVisible" title="导入学生名单" width="30%">
        <el-upload
            ref="upload"
            action=""
            :before-upload="beforeUpload"
            :auto-upload="false"
            :limit="1"
            accept=".xlsx,.xls"
            @change="handleFileChange"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div>只能上传Excel文件，且不超过5MB</div>
          </template>
        </el-upload>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleDialogCancel">取消</el-button>
            <el-button type="primary" @click="importStudents">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import store from "@/store";

const api = axios.create({
  baseURL: store.getters.getBaseURL
});

// 添加请求和响应拦截器
api.interceptors.request.use(config => {
  const token = sessionStorage.getItem('userToken');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

api.interceptors.response.use(
    response => response,
    error => {
      if (error.response?.status === 401) {
        window.location.href = '/loginAndRegister';
      }
      return Promise.reject(error);
    }
);

export default {
  data() {
    return {
      course: {
        id: this.$route.params.id,
        name: decodeURIComponent(this.$route.query.name) || '课程名称',
        avatar: ''
      },
      classList: [],
      defaultAvatar: require('@/assets/example.png'),
      isLoading: false,
      addClassForm: {
        name: '',
        totals: 0
      },
      editDialogVisible: false,
      addDialogVisible: false,
      importDialogVisible: false,
      editClassForm: {
        id: null,
        name: ''
      },
      currentEditId: null,
      currentImportClassId: null,
      uploadFile: null
    };
  },
  created() {
    this.isLoading = true;
    this.getCourseDetail();
    this.getClasses();
    this.isLoading = false;
  },
  methods: {
    openAddDialog() {
      this.addDialogVisible = true;
    },
    getCourseDetail() {
      api
          .get(`/course/${this.course.id}`)
          .then(response => {
            if (response.data.status === 'success') {
              const data = response.data.data;
              // 如果接口返回了数据，则更新course
              if (data) {
                this.course = {
                  ...this.course,
                  ...data
                };
              }
            } else {
              ElMessage.error(response.data.info || '获取课程详情失败');
            }
          })
          .catch(error => {
            console.error('Error fetching course detail:', error);
            ElMessage.error('获取课程详情失败');
          });
    },
    getClasses() {
      api
          .get(`/sys_class/${this.course.id}`)
          .then(response => {
            if (response.data.status === 'success') {
              this.classList = response.data.data;
            } else {
              ElMessage.error(response.data.info || '获取班级列表失败');
            }
          })
          .catch(error => {
            console.error('Error fetching class list:', error);
            ElMessage.error('获取班级列表失败');
          });
    },
    addClass() {
      if (!this.addClassForm.name) {
        ElMessage.error('请输入班级名称');
        return;
      }

      const classData = {
        name: this.addClassForm.name,
        cid: this.course.id,
        totals: this.addClassForm.totals
      };

      api
          .post('/sys_class', classData)
          .then(response => {
            if (response.data.status === 'success') {
              ElMessage.success('添加班级成功');
              this.getClasses();
              this.addDialogVisible = false;
              this.addClassForm.name = '';
              this.addClassForm.totals = 0;
            } else {
              ElMessage.error(response.data.info || '添加班级失败');
            }
          })
          .catch(error => {
            console.error('Error adding class:', error);
            ElMessage.error('添加班级失败');
          });
    },
    openEditDialog(row) {
      this.currentEditId = row.id;
      this.editClassForm.name = row.name;
      this.editDialogVisible = true;
    },
    updateClass() {
      if (!this.editClassForm.name) {
        ElMessage.error('请输入班级名称');
        return;
      }

      const updateData = {
        name: this.editClassForm.name
      };

      api
          .put(`/sys_class/${this.currentEditId}`, updateData)
          .then(response => {
            if (response.data.status === 'success') {
              ElMessage.success('修改班级成功');
              this.getClasses();
              this.editDialogVisible = false;
            } else {
              ElMessage.error(response.data.info || '修改班级失败');
            }
          })
          .catch(error => {
            console.error('Error updating class:', error);
            ElMessage.error('修改班级失败');
          });
    },
    deleteClass(id) {
      ElMessageBox.confirm(
          '确认要删除这个班级吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
        api
            .delete(`/sys_class/${id}`)
            .then(response => {
              if (response.data.status === 'success') {
                ElMessage.success('删除班级成功');
                this.getClasses();
              } else {
                ElMessage.error(response.data.info || '删除班级失败');
              }
            })
            .catch(error => {
              console.error('Error deleting class:', error);
              ElMessage.error('删除班级失败');
            });
      }).catch(() => {
        // 取消删除
      });
    },
    openImportDialog(row) {
      this.currentImportClassId = row.id;
      this.importDialogVisible = true;
    },
    handleFileChange(file) {
      this.uploadFile = file.raw;
    },
    handleDialogCancel() {
      this.importDialogVisible = false;
      this.uploadFile = null;
      this.$refs.upload.clearFiles();
    },
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          file.type === 'application/vnd.ms-excel';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isExcel) {
        ElMessage.error('只能上传Excel文件!');
        return false;
      }
      if (!isLt5M) {
        ElMessage.error('文件大小不能超过 5MB!');
        return false;
      }

      this.uploadFile = file.raw;
      return false; // 阻止自动上传
    },
    importStudents() {
      if (!this.uploadFile) {
        ElMessage.error('请先选择文件!');
        return;
      }

      const formData = new FormData();
      formData.append('file', this.uploadFile);
      formData.append('id', this.currentImportClassId);

      api
          .post('/excel/import', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          .then(response => {
            if (response.data.status === 'success') {
              ElMessage.success(response.data.data);
              this.getClasses();
              this.importDialogVisible = false;
              this.uploadFile = null;
              this.$refs.upload.clearFiles();
            } else {
              ElMessage.error(response.data.info || '导入失败');
            }
          })
          .catch(error => {
            console.error('Error importing students:', error);
            ElMessage.error('导入失败');
          });
    }
  }
};
</script>

<style scoped>
.course-detail-container {
  padding: 20px;
}

.course-detail-header {
  margin-bottom: 20px;
}

h2 {
  color: #333;
  font-size: 24px;
}

.course-detail-info {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
}

.course-avatar {
  flex: 0 0 150px;
}

.course-avatar-large {
  width: 150px;
  height: 150px;
  border-radius: 8px;
  object-fit: cover;
}

.course-basic-info {
  flex: 1;
}

.course-classes-section {
  margin-top: 20px;
}

h3 {
  color: #333;
  font-size: 18px;
  margin-bottom: 15px;
}

.el-table {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.class-add-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}
</style>